package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorsMapper dishFlavorsMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public PageResult pageSelectDish(DishPageQueryDTO dto) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> dishes = (Page<DishVO>) dishMapper.pageSelectDish(dish);

        dishes.forEach(a -> {
            Category category = categoryMapper.selectCategoryById(a.getCategoryId());
            a.setCategoryName(category.getName());
        });

        return new PageResult(dishes.getTotal(), dishes.getResult());
    }

    @Override
    public DishVO selectDishById(Long id) {
        Dish dish = dishMapper.selectDishById(id);
        List<DishFlavor> flavors = dishFlavorsMapper.selectByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        Category category = categoryMapper.selectCategoryById(dish.getCategoryId());
        dishVO.setCategoryName(category.getName());
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    @Override
    public List<Dish> selectDishByCategoryId(Long categoryId) {
        return dishMapper.selectDishByCategoryId(categoryId);
    }

    @Override
    @CacheEvict(cacheNames = "userCache",allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void insertDish(DishDTO dto) {
        Dish dish = new Dish();

        BeanUtils.copyProperties(dto, dish);
        dishMapper.insertDish(dish);
        List<DishFlavor> flavors = dto.getFlavors();
        if (!flavors.isEmpty()) {
            flavors.forEach(a -> {
                a.setDishId(dish.getId());
            });
            dishFlavorsMapper.insertDishFlavors(flavors);
        }
        //redisTemplate.delete("user_" + dish.getCategoryId());

    }

    @Override
    @CacheEvict(cacheNames = "userCache",allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void statusStartOrStop(Integer status, Long id) {
        Setmeal setmeal = dishMapper.selectSetmeal(id);
        if (setmeal != null) {
            setmeal.setStatus(StatusConstant.DISABLE);
            setmealMapper.updateSetmeal(setmeal);
        }
        dishMapper.updateDish(Dish.builder().status(status).id(id).build());
        //redisTemplate.delete("user_" + setmeal.getCategoryId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @CacheEvict(cacheNames = "userCache",allEntries = true)
    public void updateDish(DishDTO dto) {
        Dish dish = new Dish();

        BeanUtils.copyProperties(dto, dish);

        dishMapper.updateDish(dish);
        List<DishFlavor> flavors = dto.getFlavors();

        if (!flavors.isEmpty()) {

            dishFlavorsMapper.deleteFlavorsByDishId(dish.getId());

            flavors.forEach(a -> {
                a.setDishId(dish.getId());
            });

            dishFlavorsMapper.insertDishFlavors(flavors);
            //redisTemplate.delete("user_" + dish.getCategoryId());

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "userCache",allEntries = true)
    public void deleteDish(List<Long> ids) {

        ids.forEach(a -> {
            Dish dish = dishMapper.selectDishById(a);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            Integer count = setmealMapper.selectSetmealByDishId(a);
            if (count != 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
            dishFlavorsMapper.deleteFlavorsByDishId(a);
            //redisTemplate.delete("user_"+dish.getCategoryId());
        });

        dishMapper.deleteDishById(ids);

    }

    @Override
    public List<DishVO> getDishVO(Long categoryId) {
        List<DishVO> dishVOS = dishMapper.getDishVO(categoryId);
        for (DishVO dishVO : dishVOS) {
            List<DishFlavor> dishFlavors = dishFlavorsMapper.selectByDishId(dishVO.getId());
            if (!dishFlavors.isEmpty()) {
                dishVO.setFlavors(dishFlavors);
            }
            Category category = categoryMapper.selectCategoryById(dishVO.getCategoryId());
            dishVO.setCategoryName(category.getName());
        }
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        //valueOperations.set("user_" + categoryId, dishVOS);
        return dishVOS;
    }
}
